package com.zzl.alligator.framework.security.hanlder;

import cn.hutool.http.HttpStatus;
import com.zzl.alligator.common.constant.Constants;
import com.zzl.alligator.common.util.JsonUtils;
import com.zzl.alligator.common.util.SpringUtils;
import com.zzl.alligator.framework.async.AsyncManager;
import com.zzl.alligator.framework.security.LoginUser;
import com.zzl.alligator.framework.support.web.vo.JsonResult;
import com.zzl.alligator.management.system.domain.SysLoginRecord;
import com.zzl.alligator.management.system.service.ISysLoginRecordService;
import com.zzl.alligator.management.system.service.impl.SysLoginRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.TimerTask;

/**
 * TODO
 *
 * @author zhouziliang
 * @since 2020/6/28
 */
@Component
@Slf4j
public class LoginFailureHandler implements AuthenticationFailureHandler {
    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception)
            throws IOException, ServletException {
        log.error("登录失败", exception);
        response.setContentType("application/json;charset=UTF-8");
        JsonResult jsonResult;
        if (exception instanceof BadCredentialsException) {
            jsonResult = JsonResult.error("用户名或密码错误", HttpStatus.HTTP_UNAUTHORIZED);
        } else {
            jsonResult = JsonResult.error("登录失败", HttpStatus.HTTP_UNAUTHORIZED);
        }
        response.getWriter().write(JsonUtils
                .toJsonString(jsonResult));
        response.getWriter().flush();
        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                ISysLoginRecordService recordService = SpringUtils.getBean(SysLoginRecordService.class);
                recordService.insertSysLoginRecord(SysLoginRecord.buildLoginRecord(request, new LoginUser(),
                        Constants.FAIL, "登录失败"));
            }
        });
    }
}
